package com.zyk.scaffold.oauth.config.oauth.support;

import com.zyk.scaffold.core.context.JwtHelper;
import com.zyk.scaffold.core.context.UserContext;
import com.zyk.scaffold.common.utils.MapUtils;
import com.zyk.scaffold.oauth.domain.LocalTenantUserDetails;
import com.zyk.scaffold.oauth.framework.constants.OauthConstants;
import com.zyk.scaffold.oauth.framework.domain.OauthContext;
import com.zyk.scaffold.oauth.framework.interfaces.ITokenConvert;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;

@Component
public class LocalAccessTokenConvert implements ITokenConvert {

    @Override
    public void convert(OauthContext context, Map<String, Object> convertData) {
        LocalTenantUserDetails userDetails = (LocalTenantUserDetails) context.getUserDetails();
        convertData.put("userId", userDetails.getId());
        convertData.put("nickName", userDetails.getName());
        convertData.put("phone", userDetails.getPhone());
        convertData.put("email", userDetails.getEmail());
        convertData.put("tenantCode", userDetails.getTenantCode());
        convertData.put("tenantName", userDetails.getTenantName());
        LocalDateTime createTime = userDetails.getCreateTime();
        if(createTime != null){
            convertData.put("createTime", createTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }
        convertData.put("jwt", buildJwt(userDetails, convertData));
        convertData.put("menuApis", userDetails.getMenuApis());
        convertData.put("menuFunctions", userDetails.getMenuFunctions());
    }

    private String buildJwt(LocalTenantUserDetails userDetails, Map<String, Object> convertData) {
        UserContext userContext = new UserContext();
        userContext.setId(userDetails.getId());
        userContext.setAccount(userDetails.getAccount());
        userContext.setEmail(userDetails.getEmail());
        userContext.setName(userDetails.getName());
        userContext.setPhone(userDetails.getPhone());
        userContext.setTenantCode(userDetails.getTenantCode());
        userContext.setTenantName(userDetails.getTenantName());
        userContext.setMenuFunctions(userDetails.getMenuFunctions());
        userContext.setExpire(MapUtils.getLongValue(convertData, OauthConstants.TokenData.KEY_IS_EXPIRES_TIME));
        String jwt = JwtHelper.toJwt(userContext);
        return jwt;
    }


    @Override
    public boolean registerAccessTokenConvert(ITokenConvert tokenConvert) {
        return false;
    }

    @Override
    public boolean registerRefreshTokenConvert(ITokenConvert tokenConvert) {
        return false;
    }
}
